package elijah.eupdater.ctr;


import elijah.eupdater.bean.Result;
import elijah.eupdater.dao.TerminalDeviceMapper;
import elijah.eupdater.entity.TerminalDevice;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.annotation.PostConstruct;

@RestController("eupdater_terminal")
@RequestMapping("eupdater/terminal")
public class TerminalCtr {

    @Autowired
    private TerminalDeviceMapper terminalDeviceMapper;


//    @PostConstruct()
//    public void init() {
//        for (int i = 0; i < 200; i++) {
//            TerminalDevice terminalDevice = new TerminalDevice();
//            terminalDevice.setDeviceId(String.valueOf(i + 1));
//            terminalDevice.setPackageName("pack"+String.valueOf(i + 1));
//            int ret = terminalDeviceMapper.updateByPrimaryKey(terminalDevice);
//        }
//    }

    @PostMapping("updateTerminal")
    public Result updateTerminal(@RequestBody TerminalDevice terminalDevice) {
        int ret = terminalDeviceMapper.updateByPrimaryKey(terminalDevice);
        TerminalDevice device = terminalDeviceMapper.selectByPrimaryKey(terminalDevice.getDeviceId(), terminalDevice.getPackageName());
        return new Result(device);
    }


    public static int MAX_UPDATE_COUNT = 3;

    @GetMapping("startUpdate")
    public Result startUpdate(String deviceId, String packageName) {
        int count = terminalDeviceMapper.checkCanUpdate(deviceId, packageName, MAX_UPDATE_COUNT);
        return new Result().setCode(count > 0 ? 0 : -1);
    }


    @GetMapping("endUpdate")
    public Result endUpdate(String deviceId, String packageName) {
        int count = terminalDeviceMapper.endUpdate(deviceId, packageName);
        return new Result();
    }

    public void setMaxUpdateCount(int count) {
        MAX_UPDATE_COUNT = count;
    }

    public Boolean isDeviceLicense(String deviceId) {
        int ret = terminalDeviceMapper.isDeviceLicense(deviceId);
        return ret > 0;
    }
}
